<!-- 供应商管理-合格供应商列表  -->
<template>
  <div class="client-list">
    <pageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true">
    </pageHeader>
    <!-- <a-space class="client-list-header"> -->
    <div class="search-box">
      <div>
        <a-space>
          <div>
            <a-input-group>
              <a-select
                :style="{ width: '120px' }"
                placeholder="请选择"
                v-model="currSelectVal"
              >
                <a-option value="number">供应商编号</a-option>
                <a-option value="name">供应商名称</a-option>
                <a-option value="category"> 供应商类别</a-option>
                <a-option value="commodityCategory">供应商品类</a-option>
              </a-select>
              <a-input-search
                :style="{ width: 'auto' }"
                placeholder="请输入"
                v-model="currSelectSearch"
                @search="search"
                search-button
              />
            </a-input-group>
          </div>
          <!-- <div
            :style="{
              marginLeft: '10px',
            }"
          >
            <span> 供应商名称： </span>
            <a-input-search
              :style="{ width: 'auto' }"
              placeholder="请输入"
              v-model="currNameSearch"
              search-button
              @click="search"
            >
              <template #button-icon>
                <icon-search />
              </template>
            </a-input-search>
          </div> -->
        </a-space>
      </div>

      <div>
        <a-space>
          <a-button type="outline" @click="reset">
            <template #icon>
              <icon-refresh />
            </template>
            <template #default>重置</template>
          </a-button>
          <a-button status="success">
            <template #icon>
              <icon-download />
            </template>
            <template #default>导入</template>
          </a-button>
          <a-button status="warning">
            <template #icon>
              <icon-export rotate="-90" />
            </template>
            <template #default>导出</template>
          </a-button>
          <a-button type="primary" @click="showFormHeaderSetting"
            >表头设置</a-button
          >
        </a-space>
      </div>
    </div>
    <div style="padding: 10px">
      <!-- </a-space> -->
      <tableTurn :tableData="getData" :args="args" ref="tableTurnRef">
        <a-table-column :width="80" align="center">
          <template #title> 序号 </template>
          <template #cell="{ rowIndex }">
            {{ rowIndex + 1 }}
          </template>
        </a-table-column>
        <a-table-column
          :title="item.name"
          v-for="(item, index) in selectedHeader"
          :key="index"
          :data-index="item.code"
          align="center"
          :width="200"
        >
          <template v-if="item.code === 'createdAt'" #cell="{ record }">
            {{ dayjs(record.createdAt).format('YYYY-MM-DD HH:MM') }}
          </template>
          <template v-else-if="item.code === 'state'" #cell="{ record }">
            <span>{{ record.state === 6 ? ' 合格供应商' : '注册供应商' }}</span>
          </template>
          <template v-else-if="item.code === 'enabled'" #cell="{ record }">
            <div :class="record.enabled === 1 ? 'enabled' : 'stopusing'"
              ><span>{{ record.enabled === 1 ? '启用' : '停用' }}</span>
            </div>
          </template>
          <!-- <template v-if="item.code === 'state'" #cell="{ record }">
          {{ record.state === 1?  }}
        </template> -->
        </a-table-column>

        <!-- 操作item -->
        <a-table-column align="center" :width="200" fixed="right" title="操作">
          <template #cell="{ record }">
            <a-space>
              <!-- <a-button
                type="text"
                :style="{
                  backgroundColor: '#31C27C',
                  color: '#fff',
                }"
                
                >{{  }}</a-button
              > -->

              <a-tooltip :content="record.enabled === 1 ? '停用' : '启用'">
                <IconFont
                  type="icon-shezhi1"
                  :size="26"
                  :style="{
                    marginRight: '10px',
                    cursor: 'pointer',
                  }"
                  @click="goEnabled(record)"
                />
              </a-tooltip>
              <a-tooltip content="档案">
                <IconFont
                  type="icon-details-def"
                  :size="26"
                  :style="{
                    marginRight: '10px',
                    cursor: 'pointer',
                  }"
                  @click="goDetail(record.id)"
                />
              </a-tooltip>
              <a-tooltip content="删除">
                <a-popconfirm
                  content="确认删除？"
                  type="error"
                  @ok="deleteItem(record.id)"
                >
                  <IconFont
                    type="icon-delete"
                    :size="26"
                    :style="{
                      marginRight: '10px',
                      cursor: 'pointer',
                    }"
                  />
                </a-popconfirm>
              </a-tooltip>
            </a-space>
          </template>
        </a-table-column>
      </tableTurn>
    </div>
    <FormHeaderSetting
      v-model:visible="formHeaderSettingVisible"
      title="合格供应商列表表头设置"
      :resultList="headerSetting.list"
      @headerSave="headerSave"
      :forbidList="forbidList"
    ></FormHeaderSetting>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, computed, watchEffect, onMounted } from 'vue';
  import { useRouter } from 'vue-router';
  import { pageData as IpageData } from '@/types/global';
  import { GetSupplierLevelInfo } from '@/api/buy-management/supplier-management/base-setting';
  import {
    GetSupplierPrimaryList,
    DelSupplierPrimaryList,
    GetSupplierPrimaryHeaderList,
    PutSupplierPrimaryHeaderList,
    putSupplierPrimaryDetail,
  } from '@/api/buy-management/supplier-management/supplier-primary-list';
  import cloneDeep from 'lodash.clonedeep';
  import dayjs from 'dayjs';
  import { formHeaderSetting } from '@/types/global';
  import { cloneDeepWith } from 'lodash';

  const router = useRouter();
  const title = '合格供应商列表';
  const breadCrumb = ['采购管理', '供应商管理', '合格供应商列表'];

  const headerSetting = reactive<formHeaderSetting>({
    list: [],
  });

  const forbidList = reactive(['salesName']); // 禁止移动的表头， (销售员)

  // 表格配置
  const args = reactive({
    stripe: true,
    rowSelection: {
      type: 'checkbox',
      showCheckedAll: true,
      onlyCurrent: false,
    },
    scroll: {
      y: 500,
    },
    bordered: {
      headerCell: true,
    },
    rowKey: 'name', // 批量选择按钮以客户名称来作为key
  });
  let tableTurnRef: any = ref(); // 储存table的ref
  let currSelectVal = ref(); // 储存当前下拉选择框的值
  let currSelectSearch = ref(''); // 储存下拉选择框对应的搜索框的值
  let currNameSearch = ref(''); // 储存搜索供应商名称的值
  let isFirstSelect = ref(true);

  // 获取列表数据
  const getData = async (pageData?: any) => {
    try {
      const res = await GetSupplierPrimaryList({
        ...pageData,
        state: 6,
        name: isFirstSelect.value ? undefined : currNameSearch.value,
        [currSelectVal.value]: isFirstSelect.value
          ? undefined
          : currSelectSearch.value,
      });
      isFirstSelect.value = false;
      return Promise.resolve(res);
    } catch (err: unknown) {
      console.log(err);
    }
  };

  let levelList = reactive<any>({
    list: [],
  });
  const getLevelData = async () => {
    try {
      const { data } = await GetSupplierLevelInfo();
      levelList.list = data;
    } catch (err: unknown) {
      console.log(err);
    }
  };
  getLevelData();

  // 搜索按钮
  const search = () => {
    tableTurnRef.value.loadData();
  };
  // 重置按钮
  const reset = () => {
    currSelectSearch.value = '';
    currNameSearch.value = '';
    currSelectVal.value = '';
    tableTurnRef.value.loadData();
  };

  // 监听键盘回车，按了回车也会查询
  const keyDown = (e: any) => {
    if (e.keyCode === 13) {
      tableTurnRef.value.loadData();
    }
  };

  onMounted(() => {
    // 监听键盘事件
    window.addEventListener('keydown', keyDown);
  });

  // 获取表头设置列表
  const getHeaders = async () => {
    try {
      const tableHead = await GetSupplierPrimaryHeaderList({
        supplierType: 5,
        userId: 2,
      });
      headerSetting.list = tableHead.extends;
    } catch (error: unknown) {
      console.log(error);
    }
  };
  getHeaders();

  // 在表格上显示的表头
  const selectedHeader = computed(() => {
    const arr: formHeaderSetting['list'] = [];
    headerSetting.list.forEach((item) => {
      if (item.isDefault === 1) {
        arr.push(item);
      }
    });
    return arr;
  });

  let formHeaderSettingVisible = ref<boolean>(false); // 是否显示表头设置组件

  // 表头设置按钮
  const showFormHeaderSetting = () => {
    formHeaderSettingVisible.value = true;
  };

  // 表头设置保存后返回的自定义事件
  const headerSave = async (headerList: formHeaderSetting['list']) => {
    try {
      const data = {
        userId: 2,
        supplierType: 5,
        extend: JSON.stringify(headerList),
      };
      await PutSupplierPrimaryHeaderList(data);
      headerSetting.list = [...headerList];
    } catch (err: unknown) {
      console.log(err);
    }
  };

  let currId = ref(-1); // 储存当前选中的id

  // 去往对应的详情页面
  const goDetail = (id: number) => {
    router.push({
      name: 'ArchivalInformation',
      query: {
        id,
      },
    });
  };

  // 删除一项
  const deleteItem = async (id: number) => {
    try {
      await DelSupplierPrimaryList({
        id,
      });
      tableTurnRef.value.loadData();
    } catch (err: unknown) {
      console.log(err);
    }
  };

  const goEnabled = async (record: any) => {
    let msg = ref(JSON.parse(JSON.stringify(record)));
    msg.value.enabled = msg.value.enabled === 1 ? 2 : 1;
    await putSupplierPrimaryDetail({ ...msg.value });
    tableTurnRef.value.loadData();
  };
</script>

<style scoped lang="less">
  .search-box {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 0px 10px;
    margin-top: -7px;
  }
  :deep(.arco-space-item) {
    margin-top: 10px;
  }

  .enabled {
    width: 75px;
    height: 40px;
    background: inherit;
    background-color: rgba(49, 194, 124, 1);
    border: none;
    border-radius: 100px;
    -moz-box-shadow: none;
    -webkit-box-shadow: none;
    box-shadow: none;
    font-size: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto;
    color: aliceblue;
  }

  .stopusing {
    width: 75px;
    height: 40px;
    background: inherit;
    background-color: rgba(229, 230, 235, 1);
    border: none;
    border-radius: 100px;
    -moz-box-shadow: none;
    -webkit-box-shadow: none;
    box-shadow: none;
    font-size: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto;
    color: rgb(249, 251, 252);
  }
</style>
